package com.xmy.cultivate.service.impl;

import com.aliyun.facebody20191230.models.AddFaceResponse;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.entity.views.FaceResult;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xmy.cultivate.entity.views.ClashFace;
import com.xmy.cultivate.entity.views.ResStudentFace;
import com.xmy.cultivate.mapper.StudentFaceDataMapper;
import com.xmy.cultivate.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.Code;
import com.xmy.cultivate.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author min
 * @since 2023-01-04
 */
@Service
@Slf4j
public class StudentFaceDataServiceImpl extends ServiceImpl<StudentFaceDataMapper, StudentFaceData> implements IStudentFaceDataService {

    @Autowired
    @Lazy
    StudentFaceDataMapper studentFaceDataMapper;

    @Autowired
    @Lazy
    IFaceDbService iFaceDbService;

    @Autowired
    @Lazy
    IAliyunFaceService iAliyunFaceService;

    @Autowired
    @Lazy
    IStudentService iStudentService;

    @Autowired
            @Lazy
    IOrganizationService iOrganizationService;

    @Autowired
    @Lazy
    ILogRecordService iLogRecordService;

    @Autowired
    @Lazy
    IStudentFaceManyDetailService iStudentFaceManyDetailService;

    @Autowired
    @Lazy
    IStudentFaceDataService iStudentFaceDataService;

    @Autowired
    @Lazy
    IStudentFaceManyService iStudentFaceManyService;;

    @Autowired
    @Lazy
    IMqPushService iMqPushService;

    /**
     * 是否采集
     * @param schoolId
     * @param studentId
     * @return
     */
    public boolean isGather(Long schoolId,Long studentId){

        QueryWrapper<StudentFaceManyDetail> studentFaceDataQueryWrapper = new QueryWrapper<>();
        //studentFaceDataQueryWrapper.eq("school_id",schoolId);
        studentFaceDataQueryWrapper.eq("student_id",studentId);
        Long count =  iStudentFaceManyDetailService.count(studentFaceDataQueryWrapper);

        if (count.equals(0L)){
            return false;
        }else {
            return true;
        }
    }


    /**
     * 修改人脸数据
     * @param schoolId
     * @param studentId
     */
    @Override
    public void updateStudentFaceData(Long schoolId, Long studentId, Long toStudentId, Integer faceType) throws Exception {
        UpdateWrapper<StudentFaceData> studentFaceDataUpdateWrapper = new UpdateWrapper<>();
        studentFaceDataUpdateWrapper.eq("school_id",schoolId);
        studentFaceDataUpdateWrapper.eq("student_id",studentId);
        studentFaceDataUpdateWrapper.gt("update_level",0);
        studentFaceDataUpdateWrapper.set("student_id",toStudentId);
        studentFaceDataUpdateWrapper.set("update_level",3);//改为需要添加的人脸数据
        this.update(studentFaceDataUpdateWrapper);

        QueryWrapper<StudentFaceData> studentFaceDataQueryWrapper = new QueryWrapper<>();
        studentFaceDataQueryWrapper.eq("school_id",schoolId);
        studentFaceDataQueryWrapper.eq("student_id",toStudentId);
        studentFaceDataQueryWrapper.eq("update_level",3);
        List<StudentFaceData> studentFaceDataList = this.list(studentFaceDataQueryWrapper);
        //log.error("修改人脸数据count："+studentFaceDataList.size());
        for (StudentFaceData studentFaceData:studentFaceDataList){
            //this.addStudentFaceDb(schoolId,studentFaceData.getStudentId());
            boolean rs = this.setData(studentFaceData.getSchoolId(), studentFaceData.getStudentId().toString(), studentFaceData.getOssImage(), studentFaceData,faceType);
            if (rs){
                studentFaceData.setUpdateLevel(4);
            }else {
                studentFaceData.setUpdateLevel(200);
            }

            this.updateById(studentFaceData);
            //log.error("修改人脸数据成功");
        }
    }


    /**
     * 添加人脸数据
     * @param schoolId
     * @param studentId
     * @throws Exception
     */
    public void addStudentFaceDb(Long schoolId,Long studentId, Integer faceType) throws Exception{
        //Long schoolId = 1600459291462770690L;
        //Long studentId = 1697587971466723328L;

        QueryWrapper<StudentFaceData> studentFaceDataQueryWrapper = new QueryWrapper<>();
        studentFaceDataQueryWrapper.eq("school_id", schoolId);
        studentFaceDataQueryWrapper.eq("student_id", studentId);
        Integer rightCount = 0;
        Integer errorCount = 0;
        Integer index = 0;
        List<StudentFaceData> studentFaceDataList = this.list(studentFaceDataQueryWrapper);
        //System.out.println("studentFaceDataList:" + studentFaceDataList.size());
        for (StudentFaceData studentFaceData : studentFaceDataList) {
            boolean rs = this.setData(studentFaceData.getSchoolId(), studentFaceData.getStudentId().toString(), studentFaceData.getOssImage(), studentFaceData,faceType);
            if (rs) {
                rightCount++;
            } else {
                errorCount++;
            }
            Thread.sleep(500);
            index++;
        }
    }

    /**
     * 添加人脸数据
     *
     * @param schoolId
     * @param studentId
     * @param ossImageUrl
     * @param studentFaceDataOld
     * @param faceType 1学生，2教师
     * @return
     * @throws Exception
     */
    @Override
    public boolean setData(Long schoolId, String studentId, String ossImageUrl, StudentFaceData studentFaceDataOld, Integer faceType) throws Exception {

        FaceDb faceDb = iFaceDbService.getFaceDbOne(faceType);

        Student student = iStudentService.getById(studentId);
        String faceIdAndentityId = iAliyunFaceService.searchFaceReturnEntityId(faceDb.getDbName(), schoolId, ossImageUrl);
        if (faceIdAndentityId != null && !faceIdAndentityId.equals("error")) {
            String[] faceIdAndEntityIdArr = faceIdAndentityId.split(",");
            String faceId = faceIdAndEntityIdArr[0];
            String entityId = faceIdAndEntityIdArr[1];
            if (studentId != entityId) {
                student.setIsGather(1);
                student.setEntityId(entityId);
                iStudentService.updateById(student);
                studentFaceDataOld.setFaceId(faceId);
                studentFaceDataOld.setEntityId(Long.parseLong(entityId));
                studentFaceDataOld.setUpdateLevel(1);
                this.updateById(studentFaceDataOld);
                return true;
            }
        } else if (faceIdAndentityId != null && faceIdAndentityId.equals("error")) {
            return false;
        }

        if (iAliyunFaceService.existFaceSample(schoolId, faceDb.getDbName(), student.getId().toString())) {
            iAliyunFaceService.updateFaceSample(schoolId, faceDb.getDbName(), student.getId().toString(), student.getName());//添加人脸样本
        } else {
            iAliyunFaceService.addFaceSample(schoolId, faceDb.getDbName(), student.getId().toString(), student.getName());//添加人脸样本
        }

        student.setIsGather(1);//设置为已采集
        QueryWrapper<StudentFaceData> studentFaceDataQueryWrapper = new QueryWrapper<>();
        String extraData = student.getName().trim();
        AddFaceResponse addFaceResponse = iAliyunFaceService.addFaceData(schoolId, faceDb.getDbName(), ossImageUrl, student.getId().toString(), extraData,faceType);//添加人脸数据

        if (addFaceResponse != null && addFaceResponse.getBody() != null && addFaceResponse.getBody().getData() != null) {
            studentFaceDataOld.setEntityId(studentFaceDataOld.getStudentId());
            studentFaceDataOld.setFaceId(addFaceResponse.getBody().getData().faceId);
            studentFaceDataOld.setQualitieScore(addFaceResponse.getBody().getData().qualitieScore);
            studentFaceDataOld.setUpdateLevel(1);
            this.updateById(studentFaceDataOld);
            //System.out.println("采集成功,faceId:" + studentFaceDataOld.getFaceId());
            return true;
        } else {
            if (addFaceResponse != null && addFaceResponse.getStatusCode() == 50000) {
                return false;
            } else {
                return false;
            }
        }
    }

    /**
     * 转校更新人脸数据
     * @param studentFaceData
     * @param faceType 1学生，2教师
     * @return
     * @throws Exception
     */
    @Override
    public boolean updateStudentFace(StudentFaceData studentFaceData, Integer faceType) throws Exception {
        FaceDb faceDb = iFaceDbService.getFaceDbOne(faceType);

        String faceIdAndentityId = iAliyunFaceService.searchFaceReturnEntityId(faceDb.getDbName(), studentFaceData.getSchoolId(), studentFaceData.getOssImage());
        Long schoolId = studentFaceData.getSchoolId();
        Long studentId = studentFaceData.getStudentId();

        if (faceIdAndentityId != null && !faceIdAndentityId.equals("error")) {
            String[] faceIdAndEntityIdArr = faceIdAndentityId.split(",");
            String faceId = faceIdAndEntityIdArr[0];
            String entityId = faceIdAndEntityIdArr[1];
            if (studentFaceData.getStudentId().toString() != entityId) {
                studentFaceData.setEntityId(Long.parseLong(entityId));
                studentFaceData.setFaceId(faceId);
                studentFaceData.setUpdateLevel(1);
                studentFaceData.setQualitieScore(studentFaceData.getQualitieScore());
                this.updateById(studentFaceData);
                return true;
            }
        } else if (faceIdAndentityId != null && faceIdAndentityId.equals("error")) {
           return false;
        }
        return this.setData(schoolId,studentId.toString(),studentFaceData.getOssImage(),studentFaceData,faceType);
    }



    @Override
    public List<StudentFaceData> getDataForStudentIdNeEntityId(){
       return studentFaceDataMapper.getDataForStudentIdNeEntityId();
    }

    @Override
    public void updateFaceDataForTransfer(Long outSchoolId, Long inSchoolId, Long studentId){
        Organization outSchool = iOrganizationService.getById(outSchoolId);
        Organization inSchool = iOrganizationService.getById(outSchoolId);
        if (outSchool.getAccessKeyId() != inSchool.getAccessKeyId()){

            QueryWrapper<StudentFaceData> studentFaceDataQueryWrapper = new QueryWrapper<>();
             this.list(studentFaceDataQueryWrapper);
            List<StudentFaceData> studentFaceDataList = this.list(studentFaceDataQueryWrapper);
        }
    }

    @Override
    public IPage<ResStudentFace> getstudentFaceList(IPage<ResStudentFace> page,
                                                    String yearPart,
                                                    String quarterNum,
                                                    String schoolIdStr,
                                                    String isSigin,
                                                    String studentName){
        return studentFaceDataMapper.getstudentFaceList(page,yearPart,quarterNum,schoolIdStr,isSigin,studentName);
    }

    /**
     *
     * @param faceDbname
     * @param schoolId
     * @param ossImageUrl
     * @param student
     * @return
     * @throws Exception
     */
    @Override
    public FaceResult batchAddFaceData(String faceDbname, Long schoolId, String ossImageUrl, Student student, Integer faceType) throws Exception {

        FaceResult faceResult = new FaceResult();

        String faceIdAndentityId = iAliyunFaceService.searchFaceReturnEntityId(faceDbname, schoolId, ossImageUrl);

        if (faceIdAndentityId != null && !faceIdAndentityId.equals("error")) {
            String[] faceIdAndEntityIdArr = faceIdAndentityId.split(",");
            String faceId = faceIdAndEntityIdArr[0];
            String entityId = faceIdAndEntityIdArr[1];
            //存在相同姓名已经录过人脸
            if (student.getId().toString() != entityId) {
                faceResult.setFaceId(faceId);
                faceResult.setEntityId(entityId);
                faceResult.setSignCode("10001");
                return faceResult;
            }
        } else if (faceIdAndentityId != null && faceIdAndentityId.equals("error")) {
            LogRecord logRecord = new LogRecord();
            logRecord.setContent("ossUrl:" + ossImageUrl);
            logRecord.setRemark("人脸采集失败：" + student.getId() + ":" + student.getName());
            logRecord.setLevel(5);
            iLogRecordService.save(logRecord);

            faceResult.setSignCode("10002");
            return faceResult;
        }

        if (iAliyunFaceService.existFaceSample(schoolId, faceDbname, student.getId().toString())) {
            iAliyunFaceService.updateFaceSample(schoolId, faceDbname, student.getId().toString(), student.getName());//添加人脸样本
        } else {
            iAliyunFaceService.addFaceSample(schoolId, faceDbname, student.getId().toString(), student.getName());//添加人脸样本
        }

        AddFaceResponse addFaceResponse;
        String extraData = student.getName().trim();
        addFaceResponse = iAliyunFaceService.addFaceData(schoolId, faceDbname, ossImageUrl, student.getId().toString(), extraData,faceType);//添加人脸数据

        if (addFaceResponse != null && addFaceResponse.getBody() != null && addFaceResponse.getBody().getData() != null) {
            faceResult.setFaceId(addFaceResponse.getBody().getData().faceId);
            faceResult.setEntityId(student.getId().toString());
            faceResult.setScore(addFaceResponse.getBody().getData().qualitieScore);
            faceResult.setSignCode("10001");
            return faceResult;

        } else {
            if (addFaceResponse != null && addFaceResponse.getStatusCode() == 50000) {
                LogRecord logRecord = new LogRecord();
                logRecord.setContent("ossUrl:" + ossImageUrl);
                logRecord.setRemark("人脸采集失败：" + student.getName());
                logRecord.setLevel(5);
                iLogRecordService.save(logRecord);
                faceResult.setSignCode("10002");
                return faceResult;
            } else {
                LogRecord logRecord = new LogRecord();
                logRecord.setContent("ossUrl:" + ossImageUrl);
                logRecord.setRemark("人脸采集失败：" + student.getName());
                logRecord.setLevel(5);
                iLogRecordService.save(logRecord);
                faceResult.setSignCode("10002");
                return faceResult;
            }
        }
    }

    @Override
    public IPage<ResStudentFace> getstudentFaceList(IPage<ResStudentFace> page, Wrapper wrapper) {
        return null;
    }

    @Override
    public IPage<ClashFace> getClashStudentList(IPage<?> page, String yearPart, String quarterNum, String schoolIdStr, String studentName, String isEqName){
        return studentFaceDataMapper.getClashStudentList(page,yearPart,quarterNum,schoolIdStr,studentName,isEqName);
    }

    @Override
    public Result delFaceDataForId(Long id, Integer faceType) throws Exception {
        FaceDb faceDb = iFaceDbService.getFaceDbOne(faceType);

        StudentFaceManyDetail studentFaceManyDetail = iStudentFaceManyDetailService.getById(id);
        if (studentFaceManyDetail == null){
            return new Result(Code.ERROR,"","人脸数据不存在");
        }

        QueryWrapper<StudentFaceManyDetail> studentFaceManyDetailQueryWrapper = new QueryWrapper<>();
        studentFaceManyDetailQueryWrapper.eq("oss_image",studentFaceManyDetail.getOssImage());
        List<StudentFaceManyDetail> studentFaceManyDetailList = iStudentFaceManyDetailService.list(studentFaceManyDetailQueryWrapper);
        for (StudentFaceManyDetail studentFaceManyDetailDel:studentFaceManyDetailList){
            Organization schoolAccount = iOrganizationService.getOneForAliAccount(studentFaceManyDetailDel.getAliAccount());
            if (schoolAccount != null){
                boolean rs = iAliyunFaceService.delFaceData(schoolAccount.getId(), faceDb.getDbName(), studentFaceManyDetailDel.getFaceId());
                if (rs){
                    iStudentFaceManyDetailService.removeById(studentFaceManyDetailDel.getId());
                }
            }else {
                iStudentFaceManyDetailService.removeById(studentFaceManyDetailDel.getId());
            }

        }

        return new Result(Code.OK,"","");
    }

    @Override
    public void delFaceDataForStudentId(Long studentId, Integer faceType) throws Exception {
        FaceDb faceDb = iFaceDbService.getFaceDbOne(faceType);
        QueryWrapper<StudentFaceManyDetail> studentFaceManyDetailQueryWrapper = new QueryWrapper<>();
        studentFaceManyDetailQueryWrapper.eq("student_id",studentId);
        List<StudentFaceManyDetail> studentFaceManyDetailList = iStudentFaceManyDetailService.list(studentFaceManyDetailQueryWrapper);
        for (StudentFaceManyDetail studentFaceManyDetailDel:studentFaceManyDetailList){
            Organization schoolAccount = iOrganizationService.getOneForAliAccount(studentFaceManyDetailDel.getAliAccount());
            boolean rs = iAliyunFaceService.delFaceData(schoolAccount.getId(), faceDb.getDbName(), studentFaceManyDetailDel.getFaceId());
            if (rs){
                iStudentFaceManyDetailService.removeById(studentFaceManyDetailDel.getId());
            }
        }

        QueryWrapper<StudentFaceData> studentFaceDataQueryWrapper = new QueryWrapper<>();
        studentFaceDataQueryWrapper.eq("student_id",studentId);
        List<StudentFaceData> studentFaceDataList = iStudentFaceDataService.list(studentFaceDataQueryWrapper);
        for (StudentFaceData studentFaceData:studentFaceDataList){
            iStudentFaceDataService.removeById(studentFaceData.getId());
        }

        QueryWrapper<StudentFaceMany> studentFaceManyQueryWrapper = new QueryWrapper<>();
        studentFaceManyQueryWrapper.eq("student_id",studentId);
        List<StudentFaceMany> studentFaceManieList = iStudentFaceManyService.list(studentFaceManyQueryWrapper);
        for (StudentFaceMany studentFaceMany:studentFaceManieList){
            iStudentFaceDataService.removeById(studentFaceMany.getId());
        }

        UpdateWrapper<Student> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id",studentId);
        updateWrapper.set("is_gather",0);
        iStudentService.update(updateWrapper);

    }

    @Override
    public Result updateFaceDataForStudentId(Long studentId, Integer faceType) throws Exception {
        try{
            FaceDb faceDb = iFaceDbService.getFaceDbOne(faceType);

            QueryWrapper<Organization> organizationQueryWrapper = new QueryWrapper<>();
            organizationQueryWrapper.eq("type",1);
            organizationQueryWrapper.eq("status",1);
            organizationQueryWrapper.groupBy("ali_account");
            List<Organization> organizationList = iOrganizationService.list(organizationQueryWrapper);
            for (Organization organization:organizationList){
                QueryWrapper<StudentFaceManyDetail> studentFaceManyDetailQueryWrapper = new QueryWrapper<>();
                studentFaceManyDetailQueryWrapper.eq("ali_account",organization.getAliAccount());
                studentFaceManyDetailQueryWrapper.eq("student_id",studentId);
                List<StudentFaceManyDetail> studentFaceManyDetailList = iStudentFaceManyDetailService.list(studentFaceManyDetailQueryWrapper);
                for (StudentFaceManyDetail studentFaceManyDetail:studentFaceManyDetailList){
                    Organization schoolAccount = iOrganizationService.getOneForAliAccount(organization.getAliAccount());
                    boolean rs = iAliyunFaceService.delFaceSampleForEntityId(schoolAccount.getId(), faceDb.getDbName(), studentFaceManyDetail.getStudentId().toString());
                }
            }

            for (Organization organization:organizationList){
                QueryWrapper<StudentFaceManyDetail> studentFaceManyDetailQueryWrapper = new QueryWrapper<>();
                studentFaceManyDetailQueryWrapper.eq("ali_account",organization.getAliAccount());
                studentFaceManyDetailQueryWrapper.eq("student_id",studentId);
                List<StudentFaceManyDetail> studentFaceManyDetailList = iStudentFaceManyDetailService.list(studentFaceManyDetailQueryWrapper);
                for (StudentFaceManyDetail studentFaceManyDetail:studentFaceManyDetailList){
                    boolean rs = iMqPushService.addStudentFaceManyDetail(studentFaceManyDetail);
                    if (rs){
                        studentFaceManyDetail.setPushMqType(1);
                    }else {
                        studentFaceManyDetail.setPushMqType(0);
                    }
                    iStudentFaceManyDetailService.updateById(studentFaceManyDetail);
                }
            }
        }catch (Exception e){
            log.info(e.toString());
        }
        return new Result(Code.OK,"","");
    }

    @Override
    public List<StudentFaceData> getAtReadingStudent(String studentId,String updateLevel){
        return studentFaceDataMapper.getAtReadingStudent(studentId,updateLevel,1000000);
    }

    @Override
    @Async("onlineAsync")
    public void addFaceDataManyDetailInit(String studentId,Integer pageSize, String updateLevel) throws InterruptedException {
        List<StudentFaceData> studentFaceDataList = studentFaceDataMapper.getAtReadingStudent(studentId,updateLevel,pageSize);
        for (StudentFaceData studentFaceData:studentFaceDataList){
            Thread.sleep(1000); // 延迟1秒，1000毫秒
            //添加到多人脸库
            iStudentFaceManyDetailService.addDataBatchInit(studentFaceData);
        }
    }

    @Override
    @Async("onlineAsync")
    public void faceDataManyForStudentId(Long studentId, Integer faceType) throws Exception {

        FaceDb faceDb = iFaceDbService.getFaceDbOne(faceType);
        //先删除后更新
        QueryWrapper<Organization> organizationQueryWrapper = new QueryWrapper<>();
        organizationQueryWrapper.eq("type",1);
        organizationQueryWrapper.eq("status",1);
        organizationQueryWrapper.groupBy("ali_account");
        List<Organization> organizationList = iOrganizationService.list(organizationQueryWrapper);
        for (Organization organization:organizationList){
            QueryWrapper<StudentFaceManyDetail> studentFaceManyDetailQueryWrapper = new QueryWrapper<>();
            studentFaceManyDetailQueryWrapper.eq("ali_account",organization.getAliAccount());
            studentFaceManyDetailQueryWrapper.eq("student_id",studentId);
            studentFaceManyDetailQueryWrapper.eq("face_type",faceType);
            List<StudentFaceManyDetail> studentFaceManyDetailList = iStudentFaceManyDetailService.list(studentFaceManyDetailQueryWrapper);
            for (StudentFaceManyDetail studentFaceManyDetail:studentFaceManyDetailList){
                Organization schoolAccount = iOrganizationService.getOneForAliAccount(organization.getAliAccount());
                boolean rs = iAliyunFaceService.delFaceSampleForEntityId(schoolAccount.getId(), faceDb.getDbName(), studentFaceManyDetail.getEntityId().toString());
                if (rs){
                    iStudentFaceManyDetailService.removeById(studentFaceManyDetail);
                }
            }
        }

        QueryWrapper<StudentFaceData> studentFaceDataQueryWrapper = new QueryWrapper<>();
        studentFaceDataQueryWrapper.eq("student_id",studentId);
        studentFaceDataQueryWrapper.eq("face_type",faceType);
        studentFaceDataQueryWrapper.orderByDesc("id");
        studentFaceDataQueryWrapper.last("limit 1");
        List<StudentFaceData> studentFaceDataList = studentFaceDataMapper.selectList(studentFaceDataQueryWrapper);
        for (StudentFaceData studentFaceData:studentFaceDataList){
            Thread.sleep(1000); // 延迟1秒，1000毫秒
            //添加到多人脸库
            iStudentFaceManyDetailService.addDataBatchInit(studentFaceData);
        }
    }
}
